package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.ArticleMapper;
import com.itheima.pojo.Article;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.Result;
import com.itheima.service.ArticleService;
import com.itheima.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * @author panweiwei
 */
@Slf4j
@Service
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleMapper articleMapper;

    /**
     * 新增文章
     *
     * @param article
     * @return
     */
    @Override
    public void add(Article article) {
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        article.setCreateUser(id);
        article.setCreateTime(LocalDateTime.now());
        article.setUpdateTime(LocalDateTime.now());
        articleMapper.add(article);
    }

    /**
     * 文章分页查询
     *
     * @param pageNum    页码
     * @param pageSize   总数
     * @param categoryId 分类id
     * @param state      状态
     * @return 返回分页
     */
    @Override
    public PageBean<Article> list(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
        log.info("pageNum:{},pageSize:{}", pageNum, pageSize);
        //创建pageBean对象
        PageBean<Article> pb = new PageBean<>();
        //开始分页查询
        PageHelper.startPage(pageNum, pageSize);
        //调用mapper查询
        Map<String, Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        log.info("userId:{}", userId);
        List<Article> as = articleMapper.list(userId, categoryId, state);
        Page<Article> p = (Page<Article>) as;
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }

    /**
     * 获取文章详情
     *
     * @param id 文章id
     * @return
     */
    @Override
    public Article findById(Integer id) {
        Article article = articleMapper.findById(id);
        return article;
    }


    /**
     * 更新文章
     *
     * @param article
     * @return
     */
    @Override
    public void update(Article article) {
        article.setUpdateTime(LocalDateTime.now());
        log.info("article:{}", article);
        articleMapper.update(article);
    }

    /**
     * 根据id删除文章
     * @param id 文章主键id
     * @return
     */
    @Override
    public void deleteById(Integer id) {
        articleMapper.deleteById(id);
    }


}
